import json

import allure
import jsonpath
import pymysql
import requests
from deepdiff import DeepDiff


class ApiKey:

    def __init__(self):
        self.session = requests.Session()

    @allure.step(">>>>>>>>>发送get请求")
    def get(self, url, params=None, **kwargs):
        return self.session.get(url, params=params, **kwargs)

    @allure.step(">>>>>>>>>发送post请求")
    def post(self, url, params=None, data=None, json=None, **kwargs):
        return self.session.post(url, params=params, data=data, json=json, **kwargs)

    @allure.step(">>>>>>>>>发送put请求")
    def put(self, url, params=None, data=None, json=None, **kwargs):
        return self.session.put(url, params=params, data=data, json=json, **kwargs)

    @allure.step(">>>>>>>>>发送delete请求")
    def delete(self, url, params=None, **kwargs):
        return self.session.delete(url, params=params, **kwargs)

    @allure.step(">>>>>>>>>使用jsonpath获取结果")
    def json_path(self, res_data, j):
        if isinstance(res_data, str):
            res_data = json.loads(res_data)
        result = jsonpath.jsonpath(res_data, j)
        # 返回列表
        return result

    @allure.step(">>>>>>>>>查询数据库结果")
    def check_sql(self, sql):
        conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", database="novel",
                               charset="utf8")
        cursor = conn.cursor()
        cursor.execute(sql)
        res = cursor.fetchall()
        cursor.close()
        conn.close()
        # 返回查询到结果的集合
        return res

    @allure.step(">>>>>>>>>进行全量字段校验")
    def json_deepdiff(self, expect_result, actual_result, **kwargs):
        """
        :param expect_result: 期望结果
        :param actual_result: 实际结果
        :param kwargs:  其他相关字段：ignore_order: True忽略顺序、ignore_string_case: True忽略大小写、exclude_paths: {}忽略字段
        :return: 期望结果与实际结果相同时返回空字典{}
        """
        if isinstance(expect_result, str):
            try:
                expect_result = json.loads(expect_result)  # 尝试解析 JSON 字符串
            except json.JSONDecodeError:
                pass  # 如果不是合法 JSON，保持原样（按字符串比较）
        elif not isinstance(expect_result, (dict, list)):
            expect_result = str(expect_result)  # 非 dict/list 转字符串（如数字、布尔值）

            # 统一处理 actual_result，确保是 dict
        if isinstance(actual_result, str):
            try:
                actual_result = json.loads(actual_result)  # 尝试解析 JSON 字符串
            except json.JSONDecodeError:
                pass  # 如果不是合法 JSON，保持原样（按字符串比较）
        elif not isinstance(actual_result, (dict, list)):
            actual_result = str(actual_result)  # 非 dict/list 转字符串

            # 执行 DeepDiff 比较
        return DeepDiff(expect_result, actual_result, **kwargs)


if __name__ == '__main__':
    ak = ApiKey()
    # data = ak.post(url="http://127.0.0.1:8888/api/front/user/login", json={"username": "18855688009", "password": "xx958012725"}, headers={"Content-Type": "application/json"})
    # print(data.json())
    data = {"code":"00000","message":"一切 ok","data":[{"a":1}, {"a":2}, {"a":3}, {"a":4}, {"a":5}]}
    res_data = ak.json_path(data, "$.data[*].a")
    s1 = []
    res_data = tuple(res_data)
    print(res_data)
    print(tuple(s1))
    # # print(ak.check_sql("select book_name from book_info where id = 1334318182169681920;"))
    # a1 = {"username": 18855688009, "data": {"uid": "1", "nickName": "18855688009", "token": "e"}, "a": True}
    # a2 = {"username": 18855688009, "data": {"uid": "1", "nickName": "18855688009", "token": "a"}, "a": True}
    # print(ak.json_deepdiff(a1, a2, exclude_paths={"root['data']['token']"}, ignore_string_case=True))
    # res_sql = ak.check_sql("SELECT book_name FROM book_info WHERE book_name LIKE '%天%' OR author_name LIKE '%天%';")
    # res_sql2 = ak.check_sql("select nick_name from user_info where username=18855688007;")
    #
    #
    # # 处理查询数据库后返回的数据
    # def flatten_tuple(nested_data):
    #     """
    #     将嵌套的元组结构扁平化：
    #     1. 对于多个单元素元组组成的元组，提取所有元素组成新元组
    #     2. 对于单个多元素元组组成的元组，直接返回内部元组
    #     # 第一种类型：多个单元素元组
    #     data1 = (('从今天开始做藩王',), ('仙界之蜕变',), ('大虞天行',), ...)
    #     result1 = flatten_tuple(data1)
    #     print(result1)
    #     # 输出：('从今天开始做藩王', '仙界之蜕变', '大虞天行', ...)
    #
    #     # 第二种类型：单个多元素元组
    #     data2 = (('18855688009', 'd1034d5ceb91160d81e1dfdda2c4e0d4'),)
    #     result2 = flatten_tuple(data2)
    #     print(result2)
    #     # 输出：('18855688009', 'd1034d5ceb91160d81e1dfdda2c4e0d4')
    #
    #     # 其他类型保持原样
    #     data3 = (('a', 'b'), ('c', 'd'))
    #     result3 = flatten_tuple(data3)
    #     print(result3)
    #     # 输出：(('a', 'b'), ('c', 'd'))
    #     """
    #     # 处理空输入
    #     if not nested_data:
    #         return ()
    #
    #     # 检查是否所有元素都是单元素元组
    #     if all(isinstance(item, tuple) and len(item) == 1 for item in nested_data):
    #         return tuple(item[0] for item in nested_data)
    #
    #     # 检查是否只有一个元素且是多元素元组
    #     if len(nested_data) == 1 and isinstance(nested_data[0], tuple) and len(nested_data[0]) > 1:
    #         return nested_data[0]
    #
    #     # 其他情况直接返回原始数据
    #     return nested_data
    #
    # # print(flatten_tuple(res_sql))
    # print(flatten_tuple(res_sql2))